﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using OnlineEducation.Data;
using OnlineEducation.Models.JQueryTable;
using OnlineEducation.Helpers.JQueryTable;
using OnlineEducation.Helpers;

namespace OnlineEducation.Areas.Controllers
{
    [Area("Code")]
    [Route("[controller]/[action]")]
    [Authorize(Roles = "SuperAdmin")]
    public class HolidayController : Controller
    {

        private readonly ApplicationDbContext _context;
        private readonly ILogger _logger;
        public HolidayController(ApplicationDbContext context, ILogger<HolidayController> logger)
        {
            _context = context;
            _logger = logger;
        }


        public IActionResult Index()
        {

            return View();
        }

        [HttpPost]
        public IActionResult GetAll(DTParameters param)
        {
            var query = _context.Holidays.AsQueryable();

            var newQuery = new SortHelper<Data.Entities.Holiday>().Apply(query, param);

            var items = newQuery.Skip(param.Start).Take(param.Length).ToArray();

            var count = newQuery.Count();

            return Json(new DTResult<Data.Entities.Holiday>
            {
                draw = param.Draw,
                data = items,
                recordsFiltered = count,
                recordsTotal = count
            });
        }
        [HttpGet("{id?}")]
        public async Task<IActionResult> AddEdit(int? id)
        {
            if (id.HasValue)
            {
                return View(await _context.Holidays.FindAsync(id));
            }
            else
            {
                var template = new Data.Entities.Holiday();

                return View(template);

            }
        }
        [HttpPost]
        public async Task<IActionResult> Save([FromBody]Data.Entities.Holiday data)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (data.Id == 0)
            {
                try
                {
                    string[] strs = data.Range.Split("至");

                    if (strs.Count() != 2)
                    {
                        return BadRequest("请选择一个范围");
                    }

                    DateTime from = DateTime.Parse(strs[0]);

                    DateTime to = DateTime.Parse(strs[1]);

                    data.FromDate = from;
                    data.ToDate = to;
                    data.Status = 1;

             

                    _context.Holidays.Add(data);

                    await _context.SaveChangesAsync();

                    return Json(new { success = true, message = "新增假期成功." });

                }
                catch (Exception ex)
                {
                    return Json(new { success = false, message = ex.Message });
                }

            }
            else
            {
                try
                {

                    string[] strs = data.Range.Split("至");

                    if (strs.Count() != 2)
                    {
                        return BadRequest("请选择一个范围");
                    }

                    DateTime from = DateTime.Parse(strs[0]);

                    DateTime to = DateTime.Parse(strs[1]);

           

                    var holiday = _context.Holidays.Find(data.Id);

                    holiday.Status = data.Status;
                    holiday.FromDate = from;
                    holiday.ToDate = to;
 

                    _context.Update(holiday);

                    await _context.SaveChangesAsync();

                    return Json(new { success = true, message = "更新假期成功." });
                }
                catch (Exception ex)
                {
                    return Json(new { success = false, message = ex.Message });
                }

            }
        }

        [HttpPost("{id}")]
        public async Task<IActionResult> Delete(int? id)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            try
            {
                var code = await _context.Holidays.SingleOrDefaultAsync(m => m.Id == id);
                if (code == null)
                {
                    return NotFound();
                }

                _context.Holidays.Remove(code);

                await _context.SaveChangesAsync();

                return Json(new { success = true, message = "删除数据成功." });
            }
            catch (Exception ex)
            {

                return Json(new { success = false, message = ex.Message });
            }


        }

        [HttpPost("{id}")]
        public async Task<IActionResult> ChangeStatus(int? id)
        {
            if (!id.HasValue)
            {
                return BadRequest("id为空");
            }

            try
            {
                var code = await _context.Holidays.FindAsync(id.Value);

                if (code == null)
                {
                    return NotFound("未找到假期");
                }
                if (code.Status == 1)
                {
                    code.Status = 0;
                }
                else
                {
                    code.Status = 1;
                }

                _context.Update(code);

                await _context.SaveChangesAsync();

                return Json(new { success = true, message = "状态变更成功." });
            }
            catch (Exception ex)
            {

                return Json(new { success = false, message = ex.Message });
            }


        }
    }
}